﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MLY.Bll
{
    public class clsCsvTemplate
    {
        #region Constructors

        public clsCsvTemplate()
        {
            _db = new Dal.lqKbmDataContext();
            Old_DataRow = New_DataRow = new List<Dal.TableCsvTemplateForUser>();
            IsExist = false;
        }

        public clsCsvTemplate(int userId)
        {
        }

        #endregion

        #region Static Members

        public static List<Dal.TableCsvTemplate> getTemplatesForUser(string userId)
        {
            using (Dal.lqKbmDataContext db = new MLY.Dal.lqKbmDataContext())
            {
                List<Dal.TableCsvTemplate> result = db.TableCsvTemplates.Where(S => S.userId.ToString() == userId).OrderBy(T => T.dateAdded).ToList();
                return result;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="templateTxt">template name</param>
        /// <param name="fields">all fields in the template</param>
        /// <returns>the idx of the new added template</returns>
        public static int AddTemplate(string templateTxt, List<MLY.Dal.TableCsvTemplateForUser> fields)
        {
            using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
            {
                Dal.TableUser usr = dc.TableUsers.Where(S => S.UserId == Utils.currUserId).FirstOrDefault();
                Dal.TableCsvTemplate t = new MLY.Dal.TableCsvTemplate()
                {
                    dateAdded = DateTime.Now,
                    TableUser = usr,
                    templateName = templateTxt
                };
                dc.TableCsvTemplates.InsertOnSubmit(t);
                dc.SubmitChanges();

                foreach (var item in fields)
                {
                    MLY.Dal.TableCsvTemplateForUser newField = new MLY.Dal.TableCsvTemplateForUser()
                    {
                        TableCsvTemplate = t,
                        CsvTemplate_FieldId = item.CsvTemplate_FieldId,
                        CsvTemplate_FieldOrder = item.CsvTemplate_FieldOrder,
                        IsKey = item.IsKey,
                        FileColumnName = item.FileColumnName
                    };
                    dc.TableCsvTemplateForUsers.InsertOnSubmit(newField);
                }
                dc.SubmitChanges();
                return t.idx;
            }
        }

        public static void DeleteTemplate(int id)
        {
            using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
            {
                var x = dc.TableCsvTemplates.Where(S => S.idx == id).FirstOrDefault();
                dc.TableCsvTemplates.DeleteOnSubmit(x);
                dc.SubmitChanges();
            }
        }

        public static List<Dal.TableCsvTemplateForUser> GetTemplateFields(int templateId)
        {
            Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext();
            return dc.TableCsvTemplateForUsers.Where(S => S.templateId == templateId).OrderBy(S => S.CsvTemplate_FieldOrder).ToList();
        }

        public static string getTemplateName(int templateId)
        {
            using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
            {
                if (templateId == 0)
                    return "Empty Template";
                return dc.TableCsvTemplates.Where(S => S.idx == templateId).Select(S => S.templateName).FirstOrDefault();
            }
        }

        public static void validateCsvFieldsList(List<MLY.Dal.TableCsvTemplateForUser> fieldsToCheck)
        {
            using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
            {
                // CHECK REQUIRED FIELDS
                List<Dal.Lookup_CsvField> requiredFields = (from p in dc.Lookup_CsvFields where p.Required != null && p.Required == true select p).ToList();
                foreach (var item in requiredFields)
                {
                    if ((item.CsvField_Name != "CustomerCode" && item.CsvField_Name != "ContractorCode") || 
                        (SessParam.IsClient && item.CsvField_Name == "CustomerCode") ||
                        ((!SessParam.IsClient) && item.CsvField_Name == "ContractorCode"))
                    {
                        if (!fieldsToCheck.Select(S => S.CsvTemplate_FieldId).Contains(item.Idx))
                            throw new Exception("Template Does not contain required field:" + item.CsvField_Name);
                    }
                }

                // CHECK DUPLICATES 
                foreach (var item in fieldsToCheck)
                {
                    foreach (var item2 in fieldsToCheck)
                    {
                        if (item2 != item)
                        {
                            if (item.CsvTemplate_FieldId == item2.CsvTemplate_FieldId)
                                throw new Exception(String.Format("Field {0} Is Duplicate in the template", item.Lookup_CsvField.CsvField_Name));

                        }
                    }
                }
            }
        }

        #endregion

        #region Public Methods

        public void moveUp(int order)
        {
            Dal.TableCsvTemplateForUser old, newOne;
            old = Data.Where(S => S.CsvTemplate_FieldOrder == order).FirstOrDefault();
            newOne = Data.Where(S => S.CsvTemplate_FieldOrder > old.CsvTemplate_FieldOrder).FirstOrDefault();
            if (newOne != null)
            {
                int oldOrder = old.CsvTemplate_FieldOrder.Value;
                old.CsvTemplate_FieldOrder = newOne.CsvTemplate_FieldOrder;
                newOne.CsvTemplate_FieldOrder = oldOrder;
            }
        }

        public void moveDown(int order)
        {
            Dal.TableCsvTemplateForUser old, newOne;
            old = Data.Where(S => S.CsvTemplate_FieldOrder == order).FirstOrDefault();
            newOne = Data.OrderByDescending(S => S.CsvTemplate_FieldOrder).ToList().Where(S => S.CsvTemplate_FieldOrder < old.CsvTemplate_FieldOrder).FirstOrDefault();
            if (newOne != null)
            {
                int oldOrder = old.CsvTemplate_FieldOrder.Value;
                old.CsvTemplate_FieldOrder = newOne.CsvTemplate_FieldOrder;
                newOne.CsvTemplate_FieldOrder = oldOrder;
            }
        }

        public string[] toStringArray()
        {
            string[] retVal = new string[Old_DataRow.Count];
            List<Dal.TableCsvTemplateForUser> tmp = Old_DataRow.OrderBy(S => S.CsvTemplate_FieldOrder).ToList();
            for (int i = 0; i < Old_DataRow.Count; i++)
            {
                retVal[i] = tmp[i].Lookup_CsvField.CsvField_Name;
            }
            return retVal;
        }

        public void delOrderdField(int fieldId)
        {
            Dal.TableCsvTemplateForUser item = New_DataRow.Where(S => S.CsvTemplate_FieldId.Value == fieldId).FirstOrDefault();
            if (item != null)
                New_DataRow.Remove(item);
        }

        public void delAllFields()
        {
            New_DataRow.Clear();
        }

        public int count()
        {
            if (Old_DataRow != null)
                return Old_DataRow.Count();
            else
                return 0;
        }

        public void Save()
        {
            //if (IsExist)
            //{
            //    List<Dal.TableCsvTemplateForUser> allOld = _db.TableCsvTemplateForUsers.Where(S => S.CsvTemplate_UserID == Utils.currUserId).ToList();
            //    _db.TableCsvTemplateForUsers.DeleteAllOnSubmit(allOld);

            //}
            //_db.TableCsvTemplateForUsers.InsertAllOnSubmit(Data);
            //_db.SubmitChanges();
            //IsExist = true;

        }
        // ==================================
        #endregion

        #region Public Properties
        // ==================================

        public List<Dal.TableCsvTemplateForUser> Data
        {
            get { return New_DataRow.OrderBy(S => S.CsvTemplate_FieldOrder).ToList(); }
        }
        // ==================================

        #endregion

        #region Fields
        // ==================================

        public bool IsExist = false;
        Dal.lqKbmDataContext _db = null;
        List<Dal.TableCsvTemplateForUser> Old_DataRow = null;
        List<Dal.TableCsvTemplateForUser> New_DataRow = null;

        // ==================================
        #endregion
    }
}
